package com.ds.infra.ibatis.transaction.support;

import com.ds.infra.ibatis.transaction.Transaction;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@UtilityClass
public class TransactionSynchronizationManager {

    // 存储当前线程的资源信息
    private static final ThreadLocal<Map<Object, Object>> resources = ThreadLocal.withInitial(HashMap::new);
    // 存储当前线程的Transaction信息
    private static final ThreadLocal<Transaction> currentTransaction = new ThreadLocal<>();

    public static void bindResource(Object key, Object value) {
        Map<Object, Object> map = resources.get();
        map.put(key, value);
    }

    public static Object getResource(Object key) {
        return resources.get().get(key);
    }

    public static void bindTransaction(Transaction transaction) {
        currentTransaction.set(transaction);
    }

    public static Transaction getTransaction() {
        return currentTransaction.get();
    }

    public static void clear() {
        resources.remove();
        currentTransaction.remove();
        log.debug("Cleared transaction synchronization");
    }
}
